<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Adm_Charts extends Controller_Base_Backend {

	protected $consumer;

	public $view;

	public function before()
	{
		parent::before();
		$this->view->js["dec_highcharts"]= array(
				"type"=>"text/javascript",
				"src"=>DOC_ROOT."modules/charts/static/jscript/highcharts.js",
				);
		$this->view->js["exporting"]= array(
				"type"=>"text/javascript",
				"src"=>DOC_ROOT."modules/charts/static/jscript/exporting.js",
				);
		$this->view->js["highcharts"]= array(
				"type"=>"text/javascript",
				"src"=>DOC_ROOT."modules/charts/static/jscript/dec_highcharts.js",
				);
		$this->view->js["dashboard_ui"]= array(
				"type"=>"text/javascript",
				"src"=>DOC_ROOT."modules/charts/static/jscript/dashboard_ui.js",
				);
	}
	
		public function action_index(){
		$this->view->css["chartgen"] = array(
				"rel"=>"stylesheet",
				"href"=>DOC_ROOT."modules/charts/static/css/chartgen.css",
				"type"=>"text/css",
				"media"=>"screen",
				"charset"=>"utf-8",
			);
		$this->view->body->content = Smarty_View::factory("chart_report.tpl");
		$this->view->body->content->top_menu_bar = Smarty_View::factory('chart_report_topmenu.tpl');
		$this->view->body->content->yesterday = date("Y-m-d",mktime(0,0,0,date("m"),date("d")-1,date("Y")));
		$this->view->body->content->thirty_days_before_yesterday = date("Y-m-d",mktime(0,0,0,date("m"),date("d")-31,date("Y")));
		$this->view->body->content->last_hour = date("Y-m-d H:i:s",mktime(date("H")-1,0,0,date("m"),date("d"),date("Y")));
		$this->view->body->content->forty_eight_hours_ago = date("Y-m-d H:i:s",mktime(date("H")-49,0,0,date("m"),date("d")-31,date("Y")));
		$this->view->body->content->language = I18n::lang();
		$this->response->body($this->view);
	}
	
	public function action_load_chart(){
		//workaround for the standard filter's datepicker
		if(isset($_POST['dt_start_sf'])) $_POST['dt_start'] = $_POST['dt_start_sf'];
		if(isset($_POST['dt_end_sf'])) $_POST['dt_end'] = $_POST['dt_end_sf'];
		
		if(isset($_POST['stores_autocomplete'])) {
			if(""==$_POST['stores_autocomplete']) die(__("No stores were selected. You have to either check \"All Stores\" or select the stores you are interested in."));
			$_POST['store_link_codes'] = explode(",",$_POST['stores_autocomplete']);
			foreach($_POST['store_link_codes'] as $i=>$link_code) $_POST['store_link_codes'][$i] = trim($link_code);
			$_POST['store_link_codes'] = array_unique($_POST['store_link_codes']);
		}
		
		//workaround for the home overview calendars
		switch($_POST['chart_id']){
			case 8:
				$_POST['frequency'] = '1';
				$_POST['dt_end'] = date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y"))); //yesterday - this format has to be maintained
				$_POST['dt_start'] = date("Y-m-d",mktime(0,0,0,date("m"),date("d")-30,date("Y"))); //30days ago
				break;
			case 9:
				$_POST['frequency'] = 'hour';
				$_POST['dt_end'] = date("Y-m-d H:i:s",mktime(date("H"),0,0,date("m"),date("d"),date("Y"))); //the beggining of the last hour
				$_POST['dt_start'] = date("Y-m-d H:i:s",mktime(date("H")-48,0,0,date("m"),date("d"),date("Y"))); //48 hours ago
				break;
                        default://for charts 1-7
                            $dt_start = explode(" ",Date::get_sql_datetime($_POST['dt_start']));
                            $_POST['dt_start'] = $dt_start[0];
                            $dt_end= explode(" ",Date::get_sql_datetime($_POST['dt_end']));
                            $_POST['dt_end'] = $dt_end[0];
                            break;
			}
			
		$hash = md5(json_encode($_POST));
                
                if(Model_Chart::generate_highchart_data_file($_POST)){
				die($hash."|".$_POST['chart_id']."|".$_POST['frequency']);
			}
		$chart = new Model_Chart($_POST['chart_id']);
		$chart->set_accesses($chart->get_accesses()+1);
		$chart->save();
	}
	public function action_load_chart_filters(){
		I18n::lang($_POST['language']);
		switch($_POST['chart_id']){
			case 1:
			case 3:
			case 5:
				$filters_div = Smarty_View::factory('filters/all_but_channels.tpl');
				break;
			case 2:
			case 6://remove chart?
			case 7://remove chart?
				$filters_div = Smarty_View::factory('filters/all_but_stores.tpl');
				break;
			case 4:
				$filters_div = Smarty_View::factory('filters/all.tpl');
				break;
			default:
				die(__("Unknown Chart ID"));
			
		}
		
		die($filters_div->render());
	}
	public function action_load_chart_infos(){
		I18n::lang($_POST['language']);
		$chart = new Model_Chart($_POST['chart_id']);
		$return = __("Description").": <span id='description'><b>".__($chart->get_description())."</b></span><br/><br/>"; 
		$return .= __("Chart Best Representation").": <span id='representation'>".$chart->get_best_representations()."</span><br/>";
		$return .= __("Each Series (lines, columns, etc) represents a").": <span>".__($chart->get_series_type())."</span><br/>";
		$return .= __("X Axis Represents").": <span>".__($chart->get_x_axis())."</span><br/>";
		$return .= __("Y Axis Represents").": <span id='yaxis'>".__($chart->get_y_axis())."</span>"; 
		die($return);
	}
	public function action_load_chart_analyses(){
		I18n::lang($_POST['language']);
		$analyses = Model_Chartanalysis::load_chart_analyses($_POST['chart_id']);
		$return = '';
		foreach($analyses as $analysis){
			$formatted_dt = explode(" ",$analysis['date_time']);
			$date = explode("-",$formatted_dt[0]);
			$date = __(date("D.", mktime(0,0,0,$date[1],$date[2],$date[0]))).date(" j/M/y", mktime(0,0,0,$date[1],$date[2],$date[0]));
			$time=explode(":",$formatted_dt[1]);
			$formatted_dt = $date." - ".$time[0].":".$time[1];
			
			$return.='<div id="canalysis_'.$analysis['id'].'" class="chart_analysis_div">';
			
			$user = new Model_User($analysis['user_id']);
			$remove='';
			switch($user->get_id()){
				case 0:
					$return .= __("Review not available (creator not identified)")."(#NIU1)</div><hr/>";
					continue;
					break;
				case Model_User::get_user()->get_id():
					$remove = "<img class=\"an_remove_button\" title=\"".__("Remove")."\" src=\"".STATIC_ROOT . "images/report/remove.png\" onclick=\"remove_analysis(".$analysis['id'].",'". __("Do you really want to remove?") . "');\" /> - ";
			}
			$return.=$remove.'<span class="an_username">'.$user->get_name().' </span> <span class="an_useremail"> ('.$user->get_email().')</span><span class="an_datetime"> '.$formatted_dt.'</span><br/>';
			$return.='<span class="an_analysis">"'.$analysis['analysis'].'"</span><br/>';
			$return.='<div class="an_reviews"> <span class="an_positive_reviews">'.$analysis['positive_reviews'].'</span>';
			$return.='<button class="an_positive_reviews_but" onclick="review_analysis('.$analysis['id'].',\'positive\')"> <img src="'.STATIC_ROOT.'images/positive.png"/>'.'</button>';
			$return.='<button class="an_negative_reviews_but" onclick="review_analysis('.$analysis['id'].',\'negative\')"> <img src="'.STATIC_ROOT.'images/negative.png"/>'.'</button>';
			$return.='<span class="an_negative_reviews">'.$analysis['negative_reviews'].'</span></div>';
			$return.='</div><br/><hr/>';
		}
		die($return);
	}
	public function action_review_analysis(){
		die(Model_Chartanalysis::review_and_get_reviews($_POST['analysis_id'],$_POST['review_type'],  Model_User::get_user()->get_id()));
	}
	
//	public function action_populate_all_chart_data(){
//		$chart_id = $this->request->param("id");
//		Model_Chart::populate_chart_data($chart_id, true);
//		Request::current()->redirect("adm/".$this->request->controller());
////		$this->response->body(Json_View::factory(array("redirect"=>true, "url"=>$this->url_root."adm/charts/chartgen/")));
//	}
//	public function action_update_chart_data(){
//		$chart_id = $this->request->param("id");
//		Model_Chart::populate_chart_data($chart_id, false);
//		Request::current()->redirect("adm/".$this->request->controller());
////		$this->response->body(Json_View::factory(array("redirect"=>true, "url"=>$this->url_root."adm/charts/chartgen/")));
//	}
	public function action_en(){
		I18n::lang('en-us');
		$this->action_index();
	}
	public function action_search_stores(){
//		die("here");,
//		return "here";
		$this->response->body(Json_View::factory(Model_Store::search_store_name($_POST['expression'])));
//		return json_encode(Model_Store::serch_store_name($_POST['expression']));
	}
        
} 
